//
//  YSEmotionManager.swift
//  新浪浪
//
//  Created by mac on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class YSEmotionManager: NSObject {
    
    static var recentEmoticon: [YSEmotion] = [YSEmotion]()
    static var defaultEmoticon: [YSEmotion] = YSEmotionManager.getEmoticons("com.sina.default")
    static var emojiEmoticon: [YSEmotion] = YSEmotionManager.getEmoticons("com.apple.emoji")
    static var lxhEmoticon: [YSEmotion] = YSEmotionManager.getEmoticons("com.sina.lxh")
    
    class func getAllEmoticon()->[[[YSEmotion]]]{
        return [pageEmoticon(recentEmoticon),pageEmoticon(defaultEmoticon),pageEmoticon(emojiEmoticon),pageEmoticon(lxhEmoticon)]
    }
    
    //通过绝对路径加载到表情emoticons
    class func getEmoticons(package:String)->[YSEmotion]{
        
        var result = [YSEmotion]()
        
        let bundlePath = NSBundle .mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        let packagePath = (bundlePath as NSString).stringByAppendingPathComponent(package)
        let infoPath = (packagePath as NSString).stringByAppendingPathComponent("info.plist")
        let dic = NSDictionary (contentsOfFile: infoPath)!
        let emoticons = dic["emoticons"] as! [[String:NSObject]]
        
        for emoticon in emoticons {
            let emo = YSEmotion(dic: emoticon)
            emo.path = packagePath
            result.append(emo)
            
        }
        
        return result
    }
    
    class func addRecentEmoticon(emoticon:YSEmotion?){
        if let emo = emoticon{
            if !recentEmoticon.contains(emo){
                recentEmoticon.insert(emo, atIndex: 0)
            }
            if recentEmoticon.count > 20{
                recentEmoticon.removeLast()
            }
        }
    }
    
    //通过传入的一位数组返回二维数组
    class func pageEmoticon(emoticons:[YSEmotion])->[[YSEmotion]]{
    var result = [[YSEmotion]]()
        let count = emoticons.count
        let pages = (count - 1)/20 + 1
        for i in 0 ..< pages {
            var len = 20
            if  i == pages - 1 {
               len = count - i * 20
            }
            let subArray = (emoticons as NSArray).subarrayWithRange(NSMakeRange(i*20, len)) as! [YSEmotion]
            result.append(subArray)
        }
        
        return result
    }
    
}















